import { BorderType } from "../borderType";

/**
 * 快速边界处理 - X坐标
 */
export function getX(x: number, width: number, borderType: BorderType): number {
  if (x >= 0 && x < width) return x;

  switch (borderType) {
    case BorderType.CONSTANT:
      return -1;
    case BorderType.REPLICATE:
      return x < 0 ? 0 : width - 1;
    case BorderType.REFLECT: {
      if (width <= 1) return 0;
      let rx = x < 0 ? -x : x;
      const mod = 2 * (width - 1);
      rx %= mod;
      return rx < width ? rx : mod - rx;
    }
    default:
      return -1;
  }
}

/**
 * 快速边界处理 - Y坐标
 */
export function getY(
  y: number,
  height: number,
  borderType: BorderType,
): number {
  if (y >= 0 && y < height) return y;

  switch (borderType) {
    case BorderType.CONSTANT:
      return -1;
    case BorderType.REPLICATE:
      return y < 0 ? 0 : height - 1;
    case BorderType.REFLECT: {
      if (height <= 1) return 0;
      let ry = y < 0 ? -y : y;
      const mod = 2 * (height - 1);
      ry %= mod;
      return ry < height ? ry : mod - ry;
    }
    default:
      return -1;
  }
}

/**
 * 快速计算平均值并限制在 0-255 范围内
 */
export function avgAndClamp(sum: number, count: number): number {
  const avg = sum / count;
  return avg < 0 ? 0 : avg > 255 ? 255 : Math.round(avg);
}
